#define _CRT_SECURE_NO_WARNINGS 1
#include "mergesort.h"

void MergeSortNonR(int* a, int n)
{
	int gap = 1;
	int* tmp = (int*)malloc(n * sizeof(int));
	if (tmp == NULL)
	{
		perror("malloc");
		return;
	}
	while (gap < n)
	{

		for (int i = 0; i < n; i += 2 * gap)
		{
			int begin1 = i, end1 = i + gap - 1;
			int begin2 = i + gap, end2 = i + 2 * gap - 1;
			if (begin2 >= n || end1 >= n)
			{
				break;
			}
			if (end2 >= n)
			{
				end2 = n - 1;
			}
			int j = i;
			while (begin1 <= end1 && begin2 <= end2)
			{
				if (a[begin1] <= a[begin2])
				{
					tmp[j++] = a[begin1++];
				}
				else
				{
					tmp[j++] = a[begin2++];
				}
			}

			while (begin1 <= end1)
			{
				tmp[j++] = a[begin1++];
			}

			while (begin2 <= end2)
			{
				tmp[j++] = a[begin2++];
			}

	
			memcpy(a+i,tmp+i, (end2 - i + 1)*sizeof(int));
		}
		gap *= 2;
		
	}
	free(tmp);
}

void CountSort(int* a, int n)
{
	
	int max = a[0], min = a[0];
	for (int i = 1; i < n; i++)
	{
		if (a[i] > max)
		{
			max = a[i];
		}
		if (a[i] < min)
		{
			min = a[i];
		}
	}
	int* countA = (int*)calloc(max-min+1, sizeof(int));
	if (countA == NULL)
	{
		perror("calloc");
		return;
	}

	for (int i = 0; i < n; i++)
	{
		countA[a[i] - min]++;
	}
	int j = 0;
	int i = 0;
	while(i < n)
	{
		while (countA[j]--)
		{
			a[i++] = j+min;
		}
		j++;
	}
	free(countA);

}